const base = '';

let flag = false;

let PAGE = 1;

$.get('http://www.xiongmaoyouxuan.com/api/tab/1?start=0', function(res) {
    console.log('res', res);
});
$.get('http://www.xiongmaoyouxuan.com/api/tab/1/feeds?start=20&sort=0', function(res) {
    console.log('res2', res);
})


// 操作按钮
$('#control').on('click', function () {
    if ($(this).text() === '操作') {
        $('.check').show()
        $(this).text('取消')
    } else {
        $('.check').hide()
        $(this).text('操作')
    }

})

// 删除按钮
$('#del').on('click', function () {
    let dataArray = getCheckID()
    let len = dataArray.length;
    dataArray.forEach(function (ID, i) {
        $.ajax({
            url: '/tour/delete',
            type: 'delete',
            dataType: 'JSON',
            data: {
                id: ID
            },
            headers: {
                authorization: localStorage.getItem('token')
            },
            success: function (msg) {
                if (i !== len - 1) return
                // 从dom节点中删除列表
                removeList();
            }
        })
    })

})

// 获取选中的input
const getCheckID = function () {
    let input = $('.check:checked')
    let data = [];
    input.each(function (i, el) {
        data.push($(el).attr('data-id'))
    })
    return data
}

// 删除选中的list
const removeList = function () {
    $('.check:checked').parent().remove()
    popup()
}

// 滚动加载数据
$(window).scroll(function () {
    let top = $(window).scrollTop();
    let height = $(window).height();
    let tall = $(document).height();
    if (top + height === tall) {
        PAGE++
        fresh(PAGE)
    }
})

// 登录注册页面
// Window: hashchange event
window.addEventListener('hashchange', function () {
    let hash = location.hash.slice(1);
    if (hash) {
        route[hash]()
    } else {
        console.log('返回首页')
    }

})

// 路由定义
const route = {
    login: function () {
        templa('登录', 'login')
    },
    sign: function () {
        templa('注册', 'sign')
    }
}

// 加载模板
function templa(id, cla) {
    let data = {
        id: id,
        name: cla
    }
    let html = template('loginTpl', data)

    let div = document.createElement('div');
    div.className = 'login'
    div.innerHTML = html;
    document.body.append(div)

    // 事件绑定
    $('#back').on('click', comingBack)
    // 登录
    $('#login') && $('#login').on('click', onLogin)
    // 注册
    $('#sign') && $('#sign').on('click', onSign)
}

// 返回
function comingBack() {
    // $('#back').unbind('click', comingBack)
    // // 登录
    // $('#login') && $('#login').unbind('click', onLogin)
    // // 注册
    // $('#sign') && $('#sign').unbind('click', onSign)
    $('.login').remove()
    history.back()
}

// 登录事件
function onLogin() {
    let data = getDAta()
    $.ajax({
        type: 'POST',
        datatype: 'JSON',
        url: base + '/user/login',
        data: {
            username: data.user,
            password: data.psw
        },
        success: function (msg) {
            let status = msg.status;
            if (status === 200) {
                localStorage.setItem('token', `Bearer ${msg.data.token}`)
                flag = true;
                fresh()
                popup('登录成功')
            } else {
                console.log('登录失败')
            }
        }

    })
}

// 注册事件
function onSign() {
    let data = getDAta()
    $.ajax({
        type: "POST",
        datatype: "JSON",
        url: base + '/user/registary',
        data: {
            username: data.user,
            password: data.psw
        },
        success: function (msg) {
            console.log(msg)
            popup('注册成功')
        }
    })
}

// 收集用户提交数据
function getDAta() {
    let data = {};
    $('.weui-input').each(function (i, el) {
        let key = $(el).attr('name')
        data[key] = $(el).val()
    })
    return data
}

// 加载新闻列表页
const fresh = function (PAGE) {
    $.ajax({
        url: base + '/tour/lists',
        type: 'GET',
        dataType: 'JSON',
        data: {
            page: PAGE,
            pageSize: 15
        },
        headers: {
            authorization: localStorage.getItem('token')
        },
        success: function (msg) {
            render(msg.data)
        }
    })

}

// 渲染
function render(data) {
    let fragment = new DocumentFragment();
    $('#LoginToRemind').hide()
    data.forEach(function (el, i) {
        let link = el.link;
        let a = document.createElement('a')
        a.className = 'weui-media-box weui-media-box_appmsg';
        a.href = link;
        let html = template('newList', el)
        a.innerHTML = html;
        fragment.append(a)
    });

    $('.weui-panel__bd').append(fragment)
    if (flag === true) {
        $('.button-sp-area>a').removeClass('weui-btn_disabled')
    } else {
        $('.button-sp-area>a').addClass('weui-btn_disabled')
    }

}

function popup() {
    let Dialog = $('#toast')
    Dialog.show()
    setTimeout(function () {
        Dialog.hide()
    }, 800)
}

const login = {
    init: function() {
        const token = localStorage.getItem('token');
        if(token) {
            $('#login,#restarty').hide()
        }
        else {
            $('#login,#restarty').show()
        }
    },
    getForm: function() {
        return {
            username: '',
            password: ''
        }
    },
    checkForm: function() {

        return true
    },
    submitForm: function(success) {
        const form = this.getForm();
        if(!this.checkForm(form)) {
            return ''
        }
        $.ajax({
            data:form,
            success: success
        })
    }
}

login.init();

$('#submit').click(function() {
    login.submitForm(function() {
        // 跳转到首页
    })
})

const registary = {

}

const router = {
    init: function() {
        this.hashChange();
    },
    back: function(callback) {
        // history.back();
        // 重新设置hash ='
        callback();

    },
    go: function(pageName, params) {
        // 把参数放到hash 后的query
        // 修改hash
    },
    hashChange: function() {
        window.addEventListener('hashchange', function() {
            // 获取hash 值 根据值跳转对应的页面
            const pageName = {
                index:'#index',
                login: '#login',
                edit:'#edit'
            }[hash];
            let edit = ''
            if(hash == 'edit') {
                edit = template(pageName, listData)
                $(edit)
            }
           document.body.append($(pageName)[0])
        }, false)
    }
}
router.back(function() {
    loginPage.remove();
})
const index = {
    page: 1,
    pageSize: 12,
    finish: false,
    loading: false,
    init: function() {
        this.getLists()
    },
    getLists: function() {
        if(this.finish)return;
        this.page++;
        this.loading = true;
        $.ajax({
            success: function(res) {
                this.loading = false;
                if(res && res.data && res.data.lists) {
                    this.render(res.data.lists);
                }
                else {
                    this.finish = true
                    // 没有数据了
                }
            }.bind(this),
            fail: function() {
                this.loading = false;
            }
        })
    },
    render: function(lists) {
        // 渲染模板
    },
    scrollBottom: function() {
        // 监听滚动 触发 getLists
    }
}

const batch = {
    showCheck: function() {

    },
    hideCheck: function() {

    },
    toggleCheck: function() {
        if(state == 1) {
            this.showCheck();
        }
        else {
            this.hideCheck();
        }
    },
    getCheckedLists: function() {
        return {id: 90}
    },

    deleteHandler: function(id, callback) {
        $.ajax({
            success: function() {
                callback();
            }
        })
    },
    updateHandler: function(id) {
       router.go('updatepage',{
           id: 90
       })
    },
    addHandler: function() {
        router.go('addpage')
    }
}

batch.toggleCheck();

const edit = {
    id: '',
    loading: false,
    init: function() {
        // 判断url query中有没有id
        // 有就 修改，没有就添加
        // 有 this.id = 获取到的id
    },
    // upload title input textarea
    getForm: function() {
        return {}
    },
    checkForm: function() {

        return true
    },
    uploadPic: function(cb) {
        $.ajax({
            data: {},
            success: function(res) {
                cb(res)
            }
        })
    },
    submitForm: function() {
        const form = getForm();

        if(!this.checkForm(form)) {
            return 
        }
        this.loading = true;
        util.toggleLoading(this.loading)
        const self = this;
        this.uploadPic(function(picPath) {
            if(this.id) {
                form.id = this.id;
            }
            form.img = picPath;
            $.ajax({
                data:form,
                success:function() {
                    
                },
                fail: function() {
                    
                },
                complete: function() {
                    self.loading = false;
                    util.toggleLoading(this.loading)
                }

            })
        })
        
    }
}

const util = {
    toggleLoading: function(state) {
        if(state) {
            // 显示loading
        }
        else {
            // 隐藏loading 
        }
    },
    getQuery: function() {

    },
    dateFormat: function() {

    }
}



$(function() {
    index.init();
    router.init();

})